package com.judian.smart.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.judian.smart.activity.MainActivity;
import com.judian.smart.base.SocketMainResult;
import com.judian.smart.model.AnHong;
import com.judian.smart.model.BlueDevice;
import com.judian.smart.model.GateWay;
import com.judian.smart.model.Master;
import com.judian.smart.model.ResponseInfo;
import com.judian.smart.model.SubscribeInfo;
import com.judian.smart.model.VoiceInfo;
import com.judian.smart.net.TcpSender;
import com.judian.smart.netty.NettySocketClient;
import com.judian.smart.receiver.NetworkReceiver;
import com.judian.smart.receiver.ReceiverBroadcast;
import com.judian.smart.socket.ISocketCode;
import com.judian.smart.util.AppTools;
import com.judian.smart.util.JSONHelper;
import com.judian.smart.util.MasterUtils;
import com.judian.smart.util.ProjectUtils;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.judian.smart.base.SocketMainResult.ServiceType.APKINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.CONNECT;
import static com.judian.smart.base.SocketMainResult.ServiceType.DOWNINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.ERROR;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETANHONGINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETBLUETOOTHINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETDEVICEINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETGATEWAYINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETMASTERINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETMODEINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETMODELIST;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETSUBSCRIBEINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETVOICEINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.GETWIFIINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.LINE;
import static com.judian.smart.base.SocketMainResult.ServiceType.LOGIN;
import static com.judian.smart.base.SocketMainResult.ServiceType.REMOTECONTROLINFO;
import static com.judian.smart.base.SocketMainResult.ServiceType.REMOTEMUSIC;
import static com.judian.smart.base.SocketMainResult.ServiceType.RESPONSE;
import static com.judian.smart.base.SocketMainResult.ServiceType.SECURITYINFO;
import static com.judian.smart.constant.ServiceType.FORWARD;

//广播接收到的操作在这个服务进行处理（防止耗时操作）
public class BroadcastService extends Service {
    private static final String TAG = BroadcastService.class.getSimpleName();
    private NetworkReceiver mNetworkReceiver;  //网络广播

    @Override
    public void onCreate() {
        super.onCreate();
        mNetworkReceiver = new NetworkReceiver();
        registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); //注册网络广播
        Log.d(TAG, "生命周期 onCreate: !!!!!!!!!!");
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            Log.d(TAG, "生命周期 onStartCommand: !!!!!!!!!!");
            Context context = getBaseContext();
            assert intent.getExtras() != null;
            String result = intent.getExtras().getString("str");
            Log.d(TAG, "onStartCommand: 收到广播回码:" + result);
            ResponseInfo info = JSONHelper.parseObject(result, ResponseInfo.class);
//            Log.d(TAG, "onStartCommand: 收到广播回码:" + GsonUtils.toJson(info));
            assert info != null;
            String service = info.getMsgType();
            if (!TextUtils.isEmpty(service)) {
                SocketMainResult.ServiceType serviceType = SocketMainResult.getServiceType(service);
                switch (serviceType) {
                    case LOGIN:
                        Log.d(TAG, "switch onStartCommand: " + LOGIN);
                        if (info.getMsgState() == 2) {
                            // YYX: 2018/11/7 取消弹出登录成功的提示框
                            Objects.requireNonNull(ProjectUtils.getRootPath()).setControlState(2);
                        } else if (info.getMsgState() == 1) {
                            Objects.requireNonNull(ProjectUtils.getRootPath()).setControlState(0);
                        }
                        Log.d(TAG, "switch onStartCommand:AppTools.getCurrentTime():" +
                                AppTools.getCurrentTime() + " ________nettyLogin");
                        break;
                    case LINE:
                        Log.d(TAG, "switch onStartCommand: " + LINE);
                        if (info.getMsgState() == 1) {
                            Log.d(TAG, "onStartCommand:AppTools.getCurrentTime():" +
                                    AppTools.getCurrentTime() + " ________nettyLine");
                        }
                        break;
                    case CONNECT:
                        Log.d(TAG, "switch onStartCommand: " + CONNECT);
                        if (info != null && ReceiverBroadcast.listener != null) {
                            String toID = info.getToID();
                            Map<String, String> mp = GateWayService.mp;
                            if (GateWayService.mp.containsKey(toID)) {
                                String id = GateWayService.mp.get(toID);
                                int state = info.getMsgState();
                                assert id != null;
                                ReceiverBroadcast.listener.receiveGateWayStatus(1, Integer.parseInt(ObjectUtils.isEmpty(id) ? "0" : id), state, info.getContent());
                                context.sendBroadcast(new Intent("GateWayIsLineReceiver").putExtra("gateway_connect", true));
                                Log.d(TAG, "onReceive: BCameraID 设备ID " + toID);
                            }
                        }
                        Log.d(TAG, "onStartCommand:AppTools.getCurrentTime():" +
                                AppTools.getCurrentTime() + " ________nettyConn");
                        break;
                    case GETANHONGINFO: {   // 1:火警1
                        Log.d(TAG, "switch onStartCommand: " + GETANHONGINFO);
                        String[] results = info.getContent().split(":");
                        if (results.length == 3) {
                            AnHong anHong = new AnHong();
                            anHong.setId(Integer.parseInt(results[0]));
                            anHong.setMsgName(results[1]);
                            anHong.setMsgInfo(results[2]);
                        }
                    }
                    break;
                    case FORWARD:
                        Log.d(TAG, "switch onStartCommand: " + FORWARD);
                        if (info.getMsgState() == 1) {
                            Log.d(TAG, "onStartCommand: info.getMsgState() == 1");
                        } else {
                            List<GateWay> list = GateWayService.list;
                            if (list != null) {
                                for (int i = 0; i < list.size(); i++) {
                                    final GateWay gateWay = list.get(i);
                                    if (gateWay.getGatewayID().equals(info.getToID())) {
                                        String result1 = ISocketCode.setConnect(gateWay.getGatewayID(), gateWay.getUserName(), gateWay.getUserPassWord(), gateWay.getIsCurrent());
                                        NettySocketClient.getInstans().sendData(result1);
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    case RESPONSE:      //判斷是否當前网關列表
                        Log.d(TAG, "switch onStartCommand: " + RESPONSE);
                        List<GateWay> gateWayList = GateWayService.list;
                        for (int i = 0; i < gateWayList.size(); i++) {
                            GateWay gateway = gateWayList.get(i);
                            int gatewayTypeID = gateway.getTypeId();
                            if (gateway.getGatewayID().equals(info.getToID()) && gatewayTypeID != 3) {
                                TcpSender.dataProcess(info.getContent());
                                break;
                            }
                        }
                        break;
                    case REMOTEMUSIC:
                        Log.d(TAG, "switch onStartCommand: " + REMOTEMUSIC);
                        break;
                    case ERROR:
                        Log.d(TAG, "switch onStartCommand: " + ERROR);
                        MainActivity.mInstance.freshFindDevice();
                        break;
                    case GETMODELIST:
                        Log.d(TAG, "switch onStartCommand: " + GETMODELIST);
                        break;
                    case GETDEVICEINFO: {
                        Log.d(TAG, "switch onStartCommand: " + GETDEVICEINFO);
                        Log.d("infoDevice", info.getContent());//主机没有场景
                    }
                    break;
                    case GETMODEINFO: {
                        Log.d(TAG, "switch onStartCommand: " + GETMODEINFO);
                    }
                    break;
                    case DOWNINFO:
                        Log.d(TAG, "switch onStartCommand: " + DOWNINFO);
                        break;

                    case APKINFO:
                        Log.d(TAG, "switch onStartCommand: " + APKINFO);
                        break;
                    case GETMASTERINFO:
                        Log.d(TAG, "switch onStartCommand: " + GETMASTERINFO);
                        break;
                    case GETVOICEINFO: {
                        Log.d(TAG, "switch onStartCommand: " + GETVOICEINFO);
                        String[] voices = info.getContent().split(";");
                        if (voices.length == 5) {
                            VoiceInfo voice = new VoiceInfo();
                            voice.setId(Integer.parseInt(voices[0]));
                            voice.setVoiceName(voices[1]);
                            voice.setVoiceAnswer(voices[2]);
                            voice.setVoiceAction(voices[3]);
                            voice.setUserName(voices[4]);
                        }
                    }
                    break;
                    case GETSUBSCRIBEINFO:
                        Log.d(TAG, "switch onStartCommand: " + GETSUBSCRIBEINFO);
                        String[] voices = info.getContent().split(";");
                        if (voices.length == 7) {
                            SubscribeInfo voice = new SubscribeInfo();
                            voice.setId(Integer.parseInt(voices[0]));
                            voice.setSubscribeName(voices[1]);
                            voice.setSubscribeDate(voices[2]);
                            voice.setSubscribeTime(voices[3]);
                            voice.setSubscribeEvent(voices[4]);
                            voice.setSubscribeAction(voices[5]);
                            voice.setUserName(voices[6]);
                        }
                        break;
                    case GETWIFIINFO:
                        Log.d(TAG, "switch onStartCommand: " + GETWIFIINFO);
                        JSONObject jsonObject = new JSONObject(info.getContent());
                        Master master = new Master();
                        master.setMn(jsonObject.getString("MasterName"));
                        master.setMc(jsonObject.getString("MasterMac"));
                        master.setWf(jsonObject.getString("MasterWiFi"));
                        MasterUtils.addDevice(master);
                        break;
                    case SECURITYINFO:
                        Log.d(TAG, "switch onStartCommand: " + SECURITYINFO);
                        break;
                    case GETBLUETOOTHINFO:
                        Log.d(TAG, "switch onStartCommand: " + GETBLUETOOTHINFO);
                        String[] content = info.getContent().split(":");
                        switch (content[0]) {
                            case "device":
                                BlueDevice blueDevice = new BlueDevice();
                                blueDevice.setDeviceName(content[1]);
                                blueDevice.setAddress(content[2]);
                                blueDevice.setDeviceType(Integer.parseInt(content[3]));
                                blueDevice.setBoundState(Integer.parseInt(content[4]));
                                blueDevice.setConnectState(0);
                                break;
                            case "connect":
                                break;
                            case "bound":
                                break;
                        }
                        break;
                    case GETGATEWAYINFO:
                        Log.d(TAG, "switch onStartCommand: " + GETGATEWAYINFO);
                        break;
                    case REMOTECONTROLINFO:
                        Log.d(TAG, "switch onStartCommand: " + REMOTECONTROLINFO);
                        break;
                    default:
                        break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "生命周期 onBind: !!!!!!!!!!!!!");
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNetworkReceiver);
    }
}
